﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;

namespace Common.SerialPortCommon
{
    public class SerialPortHelper
    {
        private SerialPort _port = null;
        private DelegateFun _delegateFun = null;

        public SerialPortHelper(string portName,DelegateFun method, int baudRate=9600, Parity parity=Parity.None, int dataBits=8, StopBits stopBits=0)
        {
            if (_port != null)
            {
                _port = new SerialPort(portName, baudRate, parity, dataBits, stopBits);
                _delegateFun = method;
            }
        }
        public void Open()
        {
            if(!_port.IsOpen)
            {
                _port.Open();
                _port.DataReceived +=new SerialDataReceivedEventHandler(Port_DataReceived);
            }
        }

        private void Port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            if (_delegateFun != null)
            {
                _delegateFun(_port);
            }
        }
        private bool Write(string sendData)
        {
            if (_port!=null && _port.IsOpen)
            {
                _port.Write(sendData);
                return true;
            }
            else
            {
                return false;
            }
        }
        public bool WriteLine(string sendData)
        {
            if (_port != null && _port.IsOpen)
            {
                _port.WriteLine(sendData);
                return true;
            }
            else
            {
                return false;
            }
        }

        public bool WriteBytes(byte[] bytes)
        {
            if (_port != null && _port.IsOpen)
            {
                _port.Write(bytes, 0, bytes.Length);
                return true;
            }
            else
            {
                return false;
            }
        }

        public void Stop()
        {
            if (_port != null && _port.IsOpen)
            {
                _port.Close();
            }
        }

        public delegate void DelegateFun(SerialPort port);
        
    }
}
